import 'package:dotted_decoration/dotted_decoration.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:text_gradiate/text_gradiate.dart';
import 'package:vape_xe/utils/utils.dart';
import 'package:vape_xe/values/colors.dart';
import 'package:vape_xe/widgets/widgets.dart';

import 'logic.dart';

class PlayGroundView extends GetView<PlayGroundController> {
  PlayGroundView({super.key}) {
    Get.put(PlayGroundController());
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Obx(
          () => controller.productList.isEmpty
              ? const SizedBox()
              : TabBarView(
                  controller: controller.tabController,
                  children: controller.productList.asMap().entries.map((e) => _buildProductPage(e.key, e.value)).toList(),
                  // children: controller.productList.asMap().map((e) => _buildProductPage(e)).toList(),
                ),
        ),

        Obx(
          () => controller.productList.isEmpty
              ? const SizedBox()
              : Positioned(
                  bottom: 145.h,
                  left: 0,
                  right: 0,
                  child: TabBar(
                    isScrollable: true,
                    tabAlignment: TabAlignment.start,
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    labelPadding: EdgeInsets.zero,
                    tabs: _buildTabBarTabs(),
                    controller: controller.tabController,
                    indicatorColor: Colors.transparent,

                    /// 下面横线
                    dividerHeight: 0.5.h,
                    dividerColor: Colors.white10,
                  ),
                ),
        ),

        /// 泡泡按钮
        AnimatedBuilder(
          animation: controller.buttonAnimationController,
          builder: (context, child) {
            double value, width, height;
            if (controller.buttonAnimationController.value < 0.25) {
              //宽度不变 高度增加 [宽度100 高度100-160]
              value = controller.animation1.value; //0-0.6
              width = 20.w; //为了重置
              height = 20.w * (1 + value);
            } else if (controller.buttonAnimationController.value < 0.5) {
              //宽度增加 高度减少 [宽度100-160 高度160-100]
              value = controller.animation2.value; //0.6-0
              width = 20.w * (1.6 - value);
              height = 20.w * (1 + value);
            } else if (controller.buttonAnimationController.value < 0.75) {
              //宽度减少 高度不变 [宽度160-80 高度100]
              value = controller.animation3.value; //1-0
              width = 20.w * (0.8 + 0.8 * value);
              height = 20.w;
            } else {
              //宽度增加 高度不变 [宽度80-100 高度100]
              value = controller.animation4.value; //0-1
              width = 20.w * (0.8 + 0.2 * value);
              height = 20.w;
            }
            return Align(
                alignment: Alignment.topCenter,
                child: InkWell(
                  onTap: () => controller.onUpgradeTap(),
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 6.h),
                    margin: EdgeInsets.only(top: 100.h),
                    decoration: BoxDecoration(
                      color: Colors.white10,
                      borderRadius: 100.radius,
                      border: Border.all(color: const Color(0xff6EDEF7).withOpacity(0.1), width: 1.w),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'assets/images/ic_paopao.webp',
                          width: width,
                          height: height,
                          fit: BoxFit.fill,
                        ),
                        11.vGap,
                        Obx(
                          () => Text(
                            controller.playGroundData['coin']?.toString().removeZero() ?? '',
                            style: TextStyle(
                              fontSize: 24.sp,
                              fontWeight: FontWeight.bold,
                              fontFamily: 'Montserrat',
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ));
          },
        ),
      ],
    );
  }

  Widget _buildPaopao() {
    return Column(children: [
      Container(
        width: 56.w,
        height: 56.w,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/ic_paopao.webp'),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('remaining', style: TextStyle(fontSize: 8.sp)),
            Text('03:34',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontFamily: 'Montserrat',
                  fontWeight: FontWeight.bold,
                ))
          ],
        ),
      ),
      4.hGap,
      Text('puff', style: TextStyle(fontSize: 9.sp))
    ]);
  }

  Widget _buildProductPage(int position, dynamic info) {
    return Stack(
      children: [
        /// 光晕
        Positioned(
          top: -250.h,
          left: 0,
          right: 0,
          child: Container(
            width: 700.w,
            height: 700.w,
            decoration: BoxDecoration(
              gradient: RadialGradient(
                center: Alignment.center,
                radius: 0.9,
                colors: [
                  AppColors.levelHaloColor[info['level']].withOpacity(0.38),
                  AppColors.levelHaloColor[info['level']].withOpacity(0),
                ],
                stops: const [0, 0.99],
              ),
            ),
          ),
        ),

        /// 烟杆
        Positioned(
          top: 200.h,
          left: Get.width / 2 - 150.w,
          child: netImageCached(
            info['icon'],
            width: 300.w,
            height: 377.w,
            showProgress: false,
            showError: false,
          ),
        ),

        /// 泡泡
        ...List.generate(controller.paoPaoList[position].animationController.length, (index) {
          PaoPaoPage page = controller.paoPaoList[position];
          return AnimatedBuilder(
            animation: page.animationController[index],
            builder: (context, child) {
              // 使用浮动动画或滑动动画的值来更新文字位置
              double topPosition = page.isStopped[index]
                  ? page.moveToPositionYAnimation[index].value
                  : page.floatingAnimation[index].value;
              double xPosition = page.isStopped[index] ? page.moveToPositionXAnimation[index].value : 1.0;
              double opacity = page.isStopped[index] ? page.opacityAnimation[index].value : 1.0; // 控制透明度
              double scale = page.isStopped[index] ? page.scaleAnimation[index].value : 1.0; // 控制透明度

              var paopaoPosition = page.index[index];
              return paopaoPosition % 2 == 0 //如果是双数在左边
                  ? Positioned(
                      top: topPosition.w,
                      left: controller.x[paopaoPosition].w +
                          (page.isStopped[index]
                              ? (MediaQuery.of(context).size.width / 2 - 34.w - controller.x[paopaoPosition].w) *
                                  (1 - xPosition)
                              : 0),
                      child: Transform.scale(
                        scale: scale,
                        child: Opacity(
                          opacity: opacity,
                          child: GestureDetector(
                            onTap: () => controller.onPopTap(position, index),
                            child: _buildPaopao(),
                          ),
                        ),
                      ),
                    )
                  : Positioned(
                      top: topPosition.w,
                      right: controller.x[paopaoPosition].w +
                          (page.isStopped[index]
                              ? (MediaQuery.of(context).size.width / 2 - 34.w - controller.x[paopaoPosition].w) *
                                  (1 - xPosition)
                              : 0),
                      child: Transform.scale(
                        scale: scale,
                        child: Opacity(
                          opacity: opacity,
                          child: GestureDetector(
                            onTap: () => controller.onPopTap(position, index),
                            child: _buildPaopao(),
                          ),
                        ),
                      ),
                    );
            },
          );
        }),

        /// 底部
        Positioned(
          bottom: 16.h,
          left: 0,
          right: 0,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () => Get.bottomSheet(
                  ExchangeDialogView(
                    modelNum: info['modelNum'],
                    type: info['vapeList'][0]['type'],
                    id1: info['vapeList'][0]['id'],
                    id2: info['vapeList'].length > 1 ? info['vapeList'][1]['id'] : null,
                  ),
                  isScrollControlled: true,
                ),
                child: Container(
                  width: 195.w,
                  height: 114.h,
                  margin: EdgeInsets.only(right: 8.w),
                  decoration: BoxDecoration(
                    color: Colors.white10,
                    borderRadius: 16.radius,
                  ),
                  child: Column(
                    children: [
                      SizedBox(
                        height: 83.h,
                        child: Row(
                          children: [
                            8.vGap,
                            Stack(
                              children: [
                                SizedBox(
                                  width: 60.w,
                                  height: 60.h,
                                ),
                                Positioned(
                                  left: 0,
                                  top: 0,
                                  bottom: 0,
                                  right: 0,
                                  child: Container(
                                    padding: EdgeInsets.symmetric(vertical: 4.h),
                                    child: netImageCached(
                                      info['vapeList'][0]['icon'],
                                      width: 60.w,
                                      height: 52.h,
                                      showProgress: false,
                                      showError: false,
                                    ),
                                  ),
                                ),
                                Positioned(
                                    bottom: 0,
                                    right: 0,
                                    child: Image.asset(
                                      'assets/images/ic_pg_qiehuan.webp',
                                      width: 16.w,
                                      height: 16.w,
                                    ))
                              ],
                            ),
                            8.vGap,
                            Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    info['vapeList'][0]['name'],
                                    style: TextStyle(fontSize: 11.sp, color: Colors.white),
                                  ),
                                  16.hGap,
                                  Row(
                                    children: [
                                      Image.asset(
                                        'assets/images/ic_paopao.webp',
                                        width: 14.w,
                                        height: 14.w,
                                      ),
                                      4.vGap,
                                      Text(
                                        '+${info['vapeList'][0]['coin']}',
                                        style: TextStyle(
                                          fontSize: 16.sp,
                                          fontWeight: FontWeight.bold,
                                          fontFamily: 'Montserrat',
                                          color: Colors.white,
                                        ),
                                      )
                                    ],
                                  ),
                                  Text(
                                    'Profit per hour'.tr,
                                    style: TextStyle(fontSize: 9.sp, color: Colors.white30),
                                  ),
                                ])
                          ],
                        ),
                      ),
                      Divider(height: 1.h, color: Colors.white10),
                      SizedBox(
                        height: 30.h,
                        child: info['vapeList'][0]['level'] == 0
                            ? Center(
                                child: TextGradiate(
                                  text: Text('Please add smoke bombs'.tr, style: TextStyle(fontSize: 11.sp)),
                                  colors: const [Color(0xffF5B946), Color(0xffF58546)],
                                  gradientType: GradientType.linear,
                                  begin: Alignment.centerLeft,
                                  end: Alignment.centerRight,
                                  tileMode: TileMode.clamp,
                                ),
                              )
                            : Row(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                children: [
                                  Text(
                                    'LV.${info['vapeList'][0]['level']}',
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      fontFamily: 'Montserrat',
                                      fontWeight: FontWeight.bold,
                                      color: AppColors.levelHaloColor[info['vapeList'][0]['level']],
                                    ),
                                  ),
                                  SizedBox(
                                    width: 49.w,
                                    height: 2.h,
                                    child: LinearProgressIndicator(
                                      value: double.parse(info['vapeList'][0]['percentage']?.toString() ?? '0') / 100.0,
                                      backgroundColor: Colors.white30,
                                      color: Colors.white,
                                      minHeight: 2.h,
                                      borderRadius: 100.radius,
                                    ),
                                  ),
                                  Text(
                                    '139:59:59',
                                    style: TextStyle(fontSize: 9.sp, color: Colors.white),
                                  )
                                ],
                              ),
                      ),
                    ],
                  ),
                ),
              ),
              if (info['vapeList'].length > 1)
                GestureDetector(
                  onTap: () => Get.bottomSheet(
                    ExchangeDialogView(
                      modelNum: info['modelNum'],
                      type: info['vapeList'][1]['type'],
                      id1: info['vapeList'][0]['id'],
                      id2: info['vapeList'][1]['id'],
                    ),
                    isScrollControlled: true,
                  ),
                  child: Container(
                    width: 195.w,
                    height: 114.h,
                    decoration: BoxDecoration(
                      color: Colors.white10,
                      borderRadius: 16.radius,
                    ),
                    child: Column(
                      children: [
                        SizedBox(
                          height: 83.h,
                          child: Row(
                            children: [
                              8.vGap,
                              Stack(
                                children: [
                                  SizedBox(
                                    width: 60.w,
                                    height: 60.h,
                                  ),
                                  Positioned(
                                    left: 0,
                                    top: 0,
                                    bottom: 0,
                                    right: 0,
                                    child: Container(
                                      padding: EdgeInsets.symmetric(vertical: 4.h),
                                      child: netImageCached(
                                        info['vapeList'][1]['icon'],
                                        width: 60.w,
                                        height: 52.h,
                                        showProgress: false,
                                        showError: false,
                                      ),
                                    ),
                                  ),
                                  Positioned(
                                      bottom: 0,
                                      right: 0,
                                      child: Image.asset(
                                        'assets/images/ic_pg_qiehuan.webp',
                                        width: 16.w,
                                        height: 16.w,
                                      ))
                                ],
                              ),
                              8.vGap,
                              Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      info['vapeList'][1]['name'],
                                      style: TextStyle(fontSize: 11.sp, color: Colors.white),
                                    ),
                                    16.hGap,
                                    Row(
                                      children: [
                                        Image.asset(
                                          'assets/images/ic_paopao.webp',
                                          width: 14.w,
                                          height: 14.w,
                                        ),
                                        4.vGap,
                                        Text(
                                          '+${info['vapeList'][1]['coin']}',
                                          style: TextStyle(
                                            fontSize: 16.sp,
                                            fontWeight: FontWeight.bold,
                                            fontFamily: 'Montserrat',
                                            color: Colors.white,
                                          ),
                                        )
                                      ],
                                    ),
                                    Text(
                                      'Profit per hour'.tr,
                                      style: TextStyle(fontSize: 9.sp, color: Colors.white30),
                                    ),
                                  ])
                            ],
                          ),
                        ),
                        Divider(height: 1.h, color: Colors.white10),
                        SizedBox(
                          height: 30.h,
                          child: info['vapeList'][1]['level'] == 0
                              ? Center(
                                  child: TextGradiate(
                                    text: Text('Please add smoking stick'.tr, style: TextStyle(fontSize: 11.sp)),
                                    colors: const [Color(0xffF5B946), Color(0xffF58546)],
                                    gradientType: GradientType.linear,
                                    begin: Alignment.centerLeft,
                                    end: Alignment.centerRight,
                                    tileMode: TileMode.clamp,
                                  ),
                                )
                              : Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                  children: [
                                    Text(
                                      'LV.${info['vapeList'][1]['level']}',
                                      style: TextStyle(
                                        fontSize: 12.sp,
                                        fontFamily: 'Montserrat',
                                        fontWeight: FontWeight.bold,
                                        color: AppColors.levelHaloColor[info['vapeList'][1]['level']],
                                      ),
                                    ),
                                    SizedBox(
                                      width: 49.w,
                                      height: 2.h,
                                      child: LinearProgressIndicator(
                                        value:
                                            double.parse(info['vapeList'][1]['percentage']?.toString() ?? '0') / 100.0,
                                        backgroundColor: Colors.white30,
                                        color: Colors.white,
                                        minHeight: 2.h,
                                        borderRadius: 100.radius,
                                      ),
                                    ),
                                    Text(
                                      '\u{221E}',
                                      style: TextStyle(fontSize: 9.sp, color: Colors.white),
                                    )
                                  ],
                                ),
                        ),
                      ],
                    ),
                  ),
                ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建 TabBar
  List<Widget> _buildTabBarTabs() {
    return controller.productList
        .asMap()
        .entries
        .map((entry) => AnimatedBuilder(
              animation: controller.tabController.animation!,
              builder: (ctx, snapshot) {
                final forward = controller.tabController.offset > 0;
                final backward = controller.tabController.offset < 0;
                int fromIndex;
                int toIndex;
                double progress;
                // Tab
                if (controller.tabController.indexIsChanging) {
                  fromIndex = controller.tabController.previousIndex;
                  toIndex = controller.tabController.index;
                  progress =
                      (controller.tabController.animation!.value - fromIndex).abs() / (toIndex - fromIndex).abs();
                } else {
                  // Scroll
                  fromIndex = controller.tabController.index;
                  toIndex = forward
                      ? fromIndex + 1
                      : backward
                          ? fromIndex - 1
                          : fromIndex;
                  progress = (controller.tabController.animation!.value - fromIndex).abs();
                }
                var flag = entry.key == fromIndex
                    ? 1 - progress
                    : entry.key == toIndex
                        ? progress
                        : 0.0;
                return Container(
                  height: 60.w,
                  alignment: Alignment.bottomCenter,
                  child: TweenAnimationBuilder(
                    duration: const Duration(milliseconds: 300),
                    tween: Tween(end: flag),
                    builder: (context, value, child) {
                      return Stack(
                        children: [
                          Container(
                            height: 44.w + 16.w * value,
                            width: 44.w + 16.w * value,
                            decoration: DottedDecoration(
                              shape: Shape.box,
                              color: const Color(0xffF58546).withOpacity(value / 2),
                              borderRadius:
                                  const BorderRadius.only(topLeft: Radius.circular(16), topRight: Radius.circular(16)),
                              dash: const <int>[5, 5],
                              strokeWidth: 1,
                            ),
                            child: Container(
                              decoration: const BoxDecoration(
                                color: Colors.white10,
                                borderRadius:
                                    BorderRadius.only(topLeft: Radius.circular(16), topRight: Radius.circular(16)),
                              ),
                              child: Center(
                                child: netImageCached(
                                  controller.productList[entry.key]['icon'],
                                  width: (24 + 12 * value).h,
                                  height: (24 + 12 * value).h,
                                  showProgress: false,
                                  showError: false,
                                ),
                              ),
                            ),
                          ),
                          if (controller.productList[entry.key]['coin'] > 0)
                            Positioned(
                              right: 0,
                              child: Transform.translate(
                                offset: Offset(4.w, -6.h),
                                child: Container(
                                  width: 16.w,
                                  height: 16.w,
                                  decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      border: Border.all(color: Colors.white30, width: 0.5.w),
                                      color: Colors.black),
                                  child: Center(
                                      child: Text(controller.productList[entry.key]['coin'].toString(),
                                          style: TextStyle(fontSize: 7.sp, color: Colors.white))),
                                ),
                              ),
                            ),
                        ],
                      );
                    },
                  ),
                );
              },
            ))
        .toList();
  }
}
